<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<h3>自定义事件：发布订阅模式</h3>
		<p>1.创建一个对象，存储添加的事件,例如：</p>
		<pre>
this.handle={
	'success':[fn1,fn2],
	'error':[fn3,fn4]
}
		</pre>
		<p>2.内部需要3个事件：添加事件，移除事件，触发事件</p>
		
		<script type="text/javascript">
			class MyEvent{
				constructor() {
				    this.handle={}
				}
				addEvent(eventName,fn){
					if(typeof this.handle[eventName] === 'undefined'){
						this.handle[eventName] = []
					}
					this.handle[eventName].push(fn)
				}
				removeEvent(eventName,fn){
					if(typeof this.handle[eventName] === 'undefined') return false
					let eventList = this.handle[eventName]
					for(let key in eventList){
						if(eventList[key] === fn){
							eventList.splice(key,1)
						}
					}
				}
				trigger(eventName,...value){
					if(typeof this.handle[eventName] === 'undefined') return false
						for(let i=0;i<this.handle[eventName].length;i++){
							this.handle[eventName][i].call(this,...value)
						}
				}
			}
			let myEvent = new MyEvent()
			
			function requestList(list){
				console.log('请求列表')
				console.log(list)
			}
			function getToken(val){
				console.log('获取token')
				console.log(val);
			}
			// 添加事件
			myEvent.addEvent('success',requestList)
			myEvent.addEvent('success',getToken)
			
			
			// 移除事件
			myEvent.removeEvent('success',requestList)
			
			// 触发事件
			myEvent.trigger("success",{a:1,b:2})
		</script>
	</body>
</html>
